package com.fr.security;

import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;

/**
*作者：furong
*日期：2016年10月25日
*时间：上午11:05:18
*/
public class MD5 {
    private static final String HEX_NUMS_STR = "0123456789ABCDEF";

    public static void main(String[] args) {
        System.out.println(encoder("abc"));
        System.out.println(decoder("900150983CD24FB0D6963F7D28E17F72"));
    }

    public static String encoder(String s) {
        try {
            byte[] input = s.getBytes();
            MessageDigest md = MessageDigest.getInstance("MD5");
            md.update(input);
            byte[] rs = md.digest();
            String result = byteToHexString(rs);
            return result;
        } catch (NoSuchAlgorithmException e) {
            e.printStackTrace();
        }
        return null;
    }

    public static String decoder(String s) {
        try {
            byte[] input = hexStringToByte(s);
            MessageDigest md = MessageDigest.getInstance("MD5");
            md.update(input);
            byte[] rs = md.digest();
            String result = byteToHexString(rs);
            return result;
        } catch (NoSuchAlgorithmException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        return null;
    }

    /** 
     * 将16进制字符串转换成字节数组 
     * @param hex 
     * @return 
     */
    public static byte[] hexStringToByte(String hex) {
        int len = (hex.length() / 2);
        byte[] result = new byte[len];
        char[] hexChars = hex.toCharArray();
        for (int i = 0; i < len; i++) {
            int pos = i * 2;
            result[i] = (byte) (HEX_NUMS_STR.indexOf(hexChars[pos]) << 4 | HEX_NUMS_STR.indexOf(hexChars[pos + 1]));
        }
        return result;
    }

    /**
     * 将指定byte数组转换成16进制字符串
     * @param b
     * @return
     */
    public static String byteToHexString(byte[] b) {
        StringBuffer hexString = new StringBuffer();
        for (int i = 0; i < b.length; i++) {
            String hex = Integer.toHexString(b[i] & 0xFF);
            if (hex.length() == 1) {
                hex = '0' + hex;
            }
            hexString.append(hex.toUpperCase());
        }
        return hexString.toString();
    }
}
